

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文将介绍ECMAScript6新增的代理和反射功能。">
<meta property="og:type" content="article">
<meta property="og:title" content="代理与反射(一)">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/05/02/%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84%EF%BC%88%E4%B8%80%EF%BC%89/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文将介绍ECMAScript6新增的代理和反射功能。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84.png">
<meta property="article:published_time" content="2023-05-02T00:00:00.000Z">
<meta property="article:modified_time" content="2024-02-26T12:23:49.415Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>代理与反射(一) - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="代理与反射(一)"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-02 08:00" pubdate>
          2023年05月02日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          83 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">代理与反射(一)</h1>
            
            
              <div class="markdown-body">
                
                <p>ECMAScript 6 新增的代理和反射为开发者提供了拦截并向基本操作嵌入额外行为的能力。</p>
<p>讲解 Proxy 和 Reflect 前，我们需要先了解<a href="https://airfe.gitee.io/blog/2023/05/04/%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7%E6%8F%8F%E8%BF%B0%E7%AC%A6/">属性描述符</a>的作用。</p>
<h1 id="Proxy"><a href="#Proxy" class="headerlink" title="Proxy"></a>Proxy</h1><p>而且<code>Vue2 =&gt; Vue3</code> 时，数据响应式方法从<code>Object.defineProperty()</code>方法变成了<code>Proxy()</code>。</p>
<p>代理(Proxy)能使我们开发者拥有一种间接修改底层方法的能力，从而控制用户的操作。</p>
<img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230502151112584.png" alt="image-20230502151112584" style="zoom:80%;">

<h2 id="创建空代理"><a href="#创建空代理" class="headerlink" title="创建空代理"></a>创建空代理</h2><p>最简单的代理是空代理，即除了作为一个抽象的目标对象，什么也不做。 默认情况下，在代理对象上执行的所有操作都会无障碍地传播到目标对象。</p>
<p>代理是使用 Proxy 构造函数创建的，这个构造函数接收两个参数：目标对象和处理程序对象。缺少其中任何一个参数都会抛出 TypeError。返回一个代理对象 </p>
<p>如：<code>new Proxy(target, handler);</code></p>
<p>要创建空代理，可以传一个简单的对象字面量作为处理程序对象，从而让所有操作畅通无阻地抵达目标对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> target = &#123;<br> <span class="hljs-attr">id</span>: <span class="hljs-string">&#x27;target&#x27;</span><br>&#125;; <span class="hljs-comment">//target：目标对象</span><br><span class="hljs-keyword">const</span> handler = &#123;&#125;; <span class="hljs-comment">//handler：是一个普通对象，其中可以重写底层实现</span><br><span class="hljs-comment">//创建空对象</span><br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, handler);<br><br><span class="hljs-comment">// id 属性会访问同一个值</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-property">id</span>); <span class="hljs-comment">// target</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">id</span>); <span class="hljs-comment">// target</span><br><br><span class="hljs-comment">// 给目标属性赋值会反映在两个对象上 因为两个对象访问的是同一个值</span><br>target.<span class="hljs-property">id</span> = <span class="hljs-string">&#x27;foo&#x27;</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-property">id</span>); <span class="hljs-comment">// foo</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">id</span>); <span class="hljs-comment">// foo</span><br><br><span class="hljs-comment">// 给代理属性赋值会反映在两个对象上 因为这个赋值会转移到目标对象</span><br>proxy.<span class="hljs-property">id</span> = <span class="hljs-string">&#x27;bar&#x27;</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-property">id</span>); <span class="hljs-comment">// bar</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">id</span>); <span class="hljs-comment">// bar</span><br><span class="hljs-comment">// hasOwnProperty()方法在两个地方  也都会应用到目标对象</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-title function_">hasOwnProperty</span>(<span class="hljs-string">&#x27;id&#x27;</span>)); <span class="hljs-comment">// true</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-title function_">hasOwnProperty</span>(<span class="hljs-string">&#x27;id&#x27;</span>)); <span class="hljs-comment">// true</span><br><br><span class="hljs-comment">// Proxy.prototype 是 undefined   因此不能使用 instanceof 操作符</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Proxy</span>); <span class="hljs-comment">// TypeError: Function has non-object prototype</span><br><span class="hljs-string">&#x27;undefined&#x27;</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">instanceof</span> check<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Proxy</span>); <span class="hljs-comment">// TypeError: Function has non-object prototype</span><br><span class="hljs-string">&#x27;undefined&#x27;</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">instanceof</span> check<br><br><span class="hljs-comment">// 严格相等可以用来区分代理和目标</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target === proxy); <span class="hljs-comment">// false</span><br></code></pre></td></tr></table></figure>

<h2 id="定义捕获器"><a href="#定义捕获器" class="headerlink" title="定义捕获器"></a>定义捕获器</h2><p>使用代理的主要目的是可以定义零个或多个捕获器（trap）。捕获器就是在处理程序对象中定义的“基本操作的拦截器”。</p>
<p>每次在代理对象上调用这些基本操作时，代理可以在这些操作传播到目标对象之前先调用捕获器函数，从而拦截并修改相应的行为。</p>
<p>比如，get()捕获器会接收到<strong>目标对象</strong>、<strong>要查询的属性</strong>和<strong>代理对象</strong>三个参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> target = &#123;<br>  <span class="hljs-attr">foo</span>: <span class="hljs-string">&quot;bar&quot;</span>,<br>&#125;;<br><span class="hljs-keyword">const</span> handler = &#123;<br>  <span class="hljs-comment">// 捕获器在处理程序对象中以方法名为键</span><br>  <span class="hljs-title function_">get</span>(<span class="hljs-params">trapTarget, property, receiver</span>) &#123;<br>    <span class="hljs-comment">//trapTarget - 目标对象</span><br>    <span class="hljs-comment">//property   - 要查询的属性</span><br>    <span class="hljs-comment">//receiver   - 代理对象</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;handler override&quot;</span>;<br>  &#125;,<br>&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, handler);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-property">foo</span>); <span class="hljs-comment">// bar</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">foo</span>); <span class="hljs-comment">// handler override</span><br></code></pre></td></tr></table></figure>

<h2 id="捕获器不变式"><a href="#捕获器不变式" class="headerlink" title="捕获器不变式"></a>捕获器不变式</h2><p>捕获器不变式因方法不同而异，但通常都会防止捕获器定义出现过于反常的行为。</p>
<p>比如，如果目标对象有一个不可配置且不可写的数据属性，那么在捕获器返回一个与该属性不同的值时，会抛出 TypeError：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">/*通过set铺货器设置writable为false的不可写属性时 */</span><br><span class="hljs-keyword">const</span> target = &#123;&#125;;<br><span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(target, <span class="hljs-string">&quot;foo&quot;</span>, &#123;<br>  <span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,<br>  <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span>,<br>  <span class="hljs-attr">value</span>: <span class="hljs-string">&quot;bar&quot;</span>,<br>&#125;);<br><span class="hljs-keyword">const</span> handler = &#123;<br>  <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;qux&quot;</span>;<br>  &#125;,<br>&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, handler);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">foo</span>); <span class="hljs-comment">// TypeError</span><br></code></pre></td></tr></table></figure>

<h2 id="可撤销代理"><a href="#可撤销代理" class="headerlink" title="可撤销代理"></a>可撤销代理</h2><p>有时候可能需要中断代理对象与目标对象之间的联系。</p>
<p>Proxy 也暴露了 <strong>revocable()方法</strong>，这个方法支持撤销代理对象与目标对象的关联。</p>
<p>后续可直接调用<strong>撤销函数 revoke()</strong> 来撤销代理。</p>
<p>撤销代理之后再调用代理会抛出 TypeError，撤销函数和代理对象是在实例化时同时生成的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> target = &#123;<br>  <span class="hljs-attr">foo</span>: <span class="hljs-string">&quot;bar&quot;</span>,<br>&#125;;<br><span class="hljs-keyword">const</span> handler = &#123;<br>  <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;intercepted&quot;</span>;<br>  &#125;,<br>&#125;;<br><span class="hljs-keyword">const</span> &#123; proxy, revoke &#125; = <span class="hljs-title class_">Proxy</span>.<span class="hljs-title function_">revocable</span>(target, handler);<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">foo</span>); <span class="hljs-comment">// intercepted</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(target.<span class="hljs-property">foo</span>); <span class="hljs-comment">// bar</span><br><span class="hljs-title function_">revoke</span>();<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy.<span class="hljs-property">foo</span>); <span class="hljs-comment">// TypeError</span><br></code></pre></td></tr></table></figure>

<h2 id="可嵌套代理"><a href="#可嵌套代理" class="headerlink" title="可嵌套代理"></a>可嵌套代理</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> target = &#123; <br>    <span class="hljs-attr">foo</span>: <span class="hljs-string">&#x27;bar&#x27;</span> <br>&#125;; <br><span class="hljs-keyword">const</span> firstProxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, &#123; <br>      <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123; <br>         <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;first proxy&#x27;</span>); <br>         <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">get</span>(...<span class="hljs-variable language_">arguments</span>); <br>	 &#125; <br>&#125;); <br><span class="hljs-keyword">const</span> secondProxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(firstProxy, &#123; <br>     <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) &#123; <br>         <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;second proxy&#x27;</span>); <br>         <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">get</span>(...<span class="hljs-variable language_">arguments</span>); <br>     &#125; <br>&#125;); <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(secondProxy.<span class="hljs-property">foo</span>); <br><span class="hljs-comment">// second proxy </span><br><span class="hljs-comment">// first proxy </span><br><span class="hljs-comment">// bar</span><br></code></pre></td></tr></table></figure>

<h2 id="代理的问题与不足"><a href="#代理的问题与不足" class="headerlink" title="代理的问题与不足"></a>代理的问题与不足</h2><h3 id="代理中的this"><a href="#代理中的this" class="headerlink" title="代理中的this"></a>代理中的this</h3><p>我们知道，方法中的 this 通常指向调用这个方法的对象。可是，如果目标对象依赖于对象标识，那就可能碰到意料之外的问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> wm = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>(); <br><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123; <br>    <span class="hljs-title function_">constructor</span>(<span class="hljs-params">userId</span>) &#123; <br>        wm.<span class="hljs-title function_">set</span>(<span class="hljs-variable language_">this</span>, userId); <br>    &#125; <br>    <span class="hljs-keyword">set</span> <span class="hljs-title function_">id</span>(<span class="hljs-params">userId</span>) &#123; <br>        wm.<span class="hljs-title function_">set</span>(<span class="hljs-variable language_">this</span>, userId); <br>    &#125; <br>    <span class="hljs-keyword">get</span> <span class="hljs-title function_">id</span>() &#123; <br>        <span class="hljs-keyword">return</span> wm.<span class="hljs-title function_">get</span>(<span class="hljs-variable language_">this</span>); <br>    &#125; <br>&#125;<br></code></pre></td></tr></table></figure>

<p>由于这个实现依赖 User 实例的对象标识，在这个实例被代理的情况下就会出问题：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>(<span class="hljs-number">123</span>); <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(user.<span class="hljs-property">id</span>); <span class="hljs-comment">// 123 </span><br><span class="hljs-keyword">const</span> userInstanceProxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(user, &#123;&#125;); <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(userInstanceProxy.<span class="hljs-property">id</span>); <span class="hljs-comment">// undefined</span><br></code></pre></td></tr></table></figure>

<p>这是因为 User 实例一开始使用目标对象作为 WeakMap 的键，代理对象却尝试从自身取得这个实例。</p>
<p>解决方法：把代理 User 实例改为代理 User 类本身。之后再创建代理的实例就会以代理实例作为 WeakMap 的键了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">UserClassProxy</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(<span class="hljs-title class_">User</span>, &#123;&#125;); <br><span class="hljs-keyword">const</span> proxyUser = <span class="hljs-keyword">new</span> <span class="hljs-title class_">UserClassProxy</span>(<span class="hljs-number">456</span>); <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxyUser.<span class="hljs-property">id</span>);<br></code></pre></td></tr></table></figure>

<h3 id="代理与内部槽位"><a href="#代理与内部槽位" class="headerlink" title="代理与内部槽位"></a>代理与内部槽位</h3><p>代理与内置引用类型（比如 Array）的实例通常可以很好地协同，但有些 ECMAScript 内置类型可能会依赖代理无法控制的机制，结果导致在代理上调用某些方法会出错。</p>
<p>一个典型的例子就是 Date 类型。根据 ECMAScript 规范，Date 类型方法的执行依赖 this 值上的内部槽位[[NumberDate]]。</p>
<p>代理对象上不存在这个内部槽位，而且这个内部槽位的值也不能通过普通的 get()和 set()操作访问到。</p>
<p>于是代理拦截后本应转发给目标对象的方法会抛出 TypeError：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(); <br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, &#123;&#125;); <br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(proxy <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Date</span>); <span class="hljs-comment">// true </span><br>proxy.<span class="hljs-title function_">getDate</span>(); <span class="hljs-comment">// TypeError: &#x27;this&#x27; is not a Date object</span><br></code></pre></td></tr></table></figure>

<h1 id="Reflect"><a href="#Reflect" class="headerlink" title="Reflect"></a>Reflect</h1><blockquote>
<p>Reflect（反射） 可以使代理器模拟目标对象的某些原始行为</p>
</blockquote>
<p>如果不用Reflect，通过代理设置源对象的值的方法如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> myTarget = &#123;&#125;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>    <span class="hljs-title function_">set</span>(<span class="hljs-params">target,property,value,receiver</span>) &#123;<br>        <span class="hljs-keyword">return</span> target[property] = value<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>用了Reflect之后</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> myTarget = &#123;&#125;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>    <span class="hljs-title function_">set</span>(<span class="hljs-params">target,property,value,receiver</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">set</span>(...<span class="hljs-variable language_">arguments</span>)<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<ol>
<li><p>Reflect 是什么？</p>
<ul>
<li>Reflect 是一个内置的 JS 对象，它提供了一系列方法，可以让开发者通过调用这些方法，访问一些 JS 底层功能。由于它类似于其他语言的<strong>反射</strong>，因此取名为 Reflect。</li>
</ul>
</li>
<li><p>它可以做什么？</p>
<ul>
<li>使用 Reflect 可以实现诸如：属性的赋值与取值、调用普通函数、调用构造函数、判断属性是否存在与对象中等等功能。</li>
</ul>
</li>
<li><p>这些功能不是已经存在了吗？为什么还需要用 Reflect 实现一次？</p>
<ul>
<li><p>有一个重要的理念，在 ES5 就被提出：减少魔法、让代码更加纯粹（语言的方法使用 API 实现，而不使用特殊语法实现），这种理念很大程度上是受到函数式编程的影响。</p>
</li>
<li><p>ES6 进一步贯彻了这种理念，它认为，对属性内存的控制、原型链的修改、函数的调用等等，这些都属于底层实现，属于一种魔法，因此，需要将它们提取出来，形成一个正常的 API，并高度聚合到某个对象中，于是就造就了 Reflect 对象。</p>
</li>
<li><p>因此，你可以看到 Reflect 对象中有很多的 API 都可以使用过去的某种语法或其他 API 实现。</p>
</li>
</ul>
</li>
<li><p>Reflect 里面提供了哪些 API 呢？</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>Reflect API</th>
<th>用处</th>
<th>等同于</th>
</tr>
</thead>
<tbody><tr>
<td>Reflect.get(target, propertyKey)</td>
<td>读取对象 target 的属性 propertyKey</td>
<td>对象的属性值读取操作</td>
</tr>
<tr>
<td>Reflect.set(target, propertyKey, value)</td>
<td>设置对象 target 的属性 propertyKey 的值为 value</td>
<td>对象的属性赋值操作</td>
</tr>
<tr>
<td>Reflect.has(target, propertyKey)</td>
<td>判断一个对象是否拥有一个属性</td>
<td>in 操作符</td>
</tr>
<tr>
<td>Reflect.defineProperty(target, propertyKey, attributes)</td>
<td>类似于 Object.defineProperty，不同的是如果配置出现问题，返回 false 而不是报错</td>
<td>Object.defineProperty</td>
</tr>
<tr>
<td>Reflect.deleteProperty(target, propertyKey)</td>
<td>删除一个对象的属性</td>
<td>delete 操作符</td>
</tr>
<tr>
<td>Reflect.apply(target, thisArgument, argumentsList)</td>
<td>调用一个指定的函数，并绑定 this 和参数列表</td>
<td>函数调用操作</td>
</tr>
<tr>
<td>Reflect.construct(target, argumentsList)</td>
<td>用构造函数的方式创建一个对象</td>
<td>new 操作符</td>
</tr>
</tbody></table>
<p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect">其他更多的 Reflect API</a></p>
<h1 id="代理捕获器与反射方法"><a href="#代理捕获器与反射方法" class="headerlink" title="代理捕获器与反射方法"></a>代理捕获器与反射方法</h1><p>下面是 Proxy 支持的拦截操作一览，一共 13 种。</p>
<ul>
<li>get(target, propKey, receiver)：拦截对象属性的读取，比如<code>proxy.foo</code>和<code>proxy[&#39;foo&#39;]</code>。</li>
<li>set(target, propKey, value, receiver)：拦截对象属性的设置，比如<code>proxy.foo = v</code>或<code>proxy[&#39;foo&#39;] = v</code>，返回一个布尔值。</li>
<li>has(target, propKey)：拦截<code>propKey in proxy</code>的操作，返回一个布尔值。</li>
<li>deleteProperty(target, propKey)：拦截<code>delete proxy[propKey]</code>的操作，返回一个布尔值。</li>
<li>ownKeys(target)：拦截<code>Object.getOwnPropertyNames(proxy)</code>、<code>Object.getOwnPropertySymbols(proxy)</code>、<code>Object.keys(proxy)</code>、<code>for...in</code>循环，返回一个数组。该方法返回目标对象所有自身的属性的属性名，而<code>Object.keys()</code>的返回结果仅包括目标对象自身的可遍历属性。</li>
<li>getOwnPropertyDescriptor(target, propKey)：拦截<code>Object.getOwnPropertyDescriptor(proxy, propKey)</code>，返回属性的描述对象。</li>
<li>defineProperty(target, propKey, propDesc)：拦截<code>Object.defineProperty(proxy, propKey, propDesc）</code>、<code>Object.defineProperties(proxy, propDescs)</code>，返回一个布尔值。</li>
<li>preventExtensions(target)：拦截<code>Object.preventExtensions(proxy)</code>，返回一个布尔值。</li>
<li>getPrototypeOf(target)：拦截<code>Object.getPrototypeOf(proxy)</code>，返回一个对象。</li>
<li>isExtensible(target)：拦截<code>Object.isExtensible(proxy)</code>，返回一个布尔值。</li>
<li>setPrototypeOf(target, proto)：拦截<code>Object.setPrototypeOf(proxy, proto)</code>，返回一个布尔值。如果目标对象是函数，那么还有两种额外操作可以拦截。</li>
<li>apply(target, object, args)：拦截 Proxy 实例作为函数调用的操作，比如<code>proxy(...args)</code>、<code>proxy.call(object, ...args)</code>、<code>proxy.apply(...)</code>。</li>
<li>construct(target, args)：拦截 Proxy 实例作为构造函数调用的操作，比如<code>new proxy(...args)</code>。</li>
</ul>
<p>简单介绍几个拦截方法的使用方法：</p>
<h2 id="get"><a href="#get" class="headerlink" title="get()"></a>get()</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> myTarget = &#123;&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>  <span class="hljs-title function_">get</span>(<span class="hljs-params">target, property, receiver</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;get()&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">get</span>(...<span class="hljs-variable language_">arguments</span>);<br>  &#125;,<br>&#125;);<br>proxy.<span class="hljs-property">foo</span>; <span class="hljs-comment">// 触发get()捕获器</span><br></code></pre></td></tr></table></figure>

<p>返回值</p>
<ul>
<li>返回值无限制。</li>
</ul>
<p>拦截的操作</p>
<ul>
<li>proxy.property</li>
<li>proxy[property]</li>
<li>Object.create(proxy)[property]</li>
<li>Reflect.get(proxy, property, receiver)</li>
</ul>
<p>捕获器处理程序参数</p>
<ul>
<li>target：目标对象。</li>
<li>property：引用的目标对象上的字符串键属性。</li>
<li>receiver：代理对象或继承代理对象的对象。</li>
</ul>
<p>捕获器不变式</p>
<ul>
<li>如果 target.property 不可写且不可配置，则处理程序返回的值必须与 target.property 匹配。</li>
<li>如果 target.property 不可配置且[[Get]]特性为 undefined，处理程序的返回值也必须是 undefined。</li>
</ul>
<h2 id="set"><a href="#set" class="headerlink" title="set()"></a>set()</h2><p>set()捕获器会在设置属性值的操作中被调用。对应的反射 API 方法为 Reflect.set()。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> myTarget = &#123;&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>  <span class="hljs-title function_">set</span>(<span class="hljs-params">target, property, value, receiver</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;set()&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">set</span>(...<span class="hljs-variable language_">arguments</span>);<br>  &#125;,<br>&#125;);<br>proxy.<span class="hljs-property">foo</span> = <span class="hljs-string">&quot;bar&quot;</span>; <span class="hljs-comment">// 触发set()捕获器</span><br>复制代码<br></code></pre></td></tr></table></figure>

<ol>
<li>返回值<ul>
<li>返回 true 表示成功；返回 false 表示失败，严格模式下会抛出 TypeError。</li>
</ul>
</li>
<li>拦截的操作<ul>
<li>proxy.property &#x3D; value</li>
<li>proxy[property] &#x3D; value</li>
<li>Object.create(proxy)[property] &#x3D; value</li>
<li>Reflect.set(proxy, property, value, receiver)</li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target：目标对象。</li>
<li>property：引用的目标对象上的字符串键属性。</li>
<li>value：要赋给属性的值。</li>
<li>receiver：接收最初赋值的对象。</li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>如果 target.property 不可写且不可配置，则不能修改目标属性的值。</li>
<li>如果 target.property 不可配置且[[Set]]特性为 undefined，则不能修改目标属性的值。 在严格模式下，处理程序中返回 false 会抛出 TypeError。</li>
</ul>
</li>
</ol>
<h2 id="has"><a href="#has" class="headerlink" title="has()"></a>has()</h2><p>has()捕获器会在 in 操作符中被调用。对应的反射 API 方法为 Reflect.has()。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> myTarget = &#123;&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>  <span class="hljs-title function_">has</span>(<span class="hljs-params">target, property</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;has()&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">has</span>(...<span class="hljs-variable language_">arguments</span>);<br>  &#125;,<br>&#125;);<br><span class="hljs-string">&quot;foo&quot;</span> <span class="hljs-keyword">in</span> proxy; <span class="hljs-comment">//触发 has()捕获器</span><br>复制代码<br></code></pre></td></tr></table></figure>

<ol>
<li>返回值<ul>
<li>has()必须返回布尔值，表示属性是否存在。返回非布尔值会被转型为布尔值。</li>
</ul>
</li>
<li>拦截的操作<ul>
<li>property in proxy</li>
<li>property in Object.create(proxy)</li>
<li>with(proxy) {(property);}</li>
<li>Reflect.has(proxy, property)</li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target：目标对象。</li>
<li>property：引用的目标对象上的字符串键属性。</li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>如果 target.property 存在且不可配置，则处理程序必须返回 true。</li>
<li>如果 target.property 存在且目标对象不可扩展，则处理程序必须返回 true。</li>
</ul>
</li>
</ol>
<h2 id="apply"><a href="#apply" class="headerlink" title="apply()"></a>apply()</h2><p>apply()捕获器会在调用函数时中被调用。对应的反射 API 方法为 Reflect.apply()。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> <span class="hljs-title function_">myTarget</span> = (<span class="hljs-params"></span>) =&gt; &#123;&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>  <span class="hljs-title function_">apply</span>(<span class="hljs-params">target, thisArg, ...argumentsList</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;apply()&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">apply</span>(...<span class="hljs-variable language_">arguments</span>);<br>  &#125;,<br>&#125;);<br><span class="hljs-title function_">proxy</span>(); <span class="hljs-comment">// 触发apply()捕获器</span><br>复制代码<br></code></pre></td></tr></table></figure>

<ol>
<li>返回值<ul>
<li>返回值无限制。</li>
</ul>
</li>
<li>拦截的操作<ul>
<li>proxy(…argumentsList)</li>
<li>Function.prototype.apply(thisArg, argumentsList)</li>
<li>Function.prototype.call(thisArg, …argumentsList)</li>
<li>Reflect.apply(target, thisArgument, argumentsList)</li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target：目标对象。</li>
<li>thisArg：调用函数时的 this 参数。</li>
<li>argumentsList：调用函数时的参数列表</li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>target 必须是一个函数对象。</li>
</ul>
</li>
</ol>
<h2 id="construct"><a href="#construct" class="headerlink" title="construct()"></a>construct()</h2><p>construct()捕获器会在 new 操作符中被调用。对应的反射 API 方法为 Reflect.construct()。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> myTarget = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;&#125;;<br><span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(myTarget, &#123;<br>  <span class="hljs-title function_">construct</span>(<span class="hljs-params">target, argumentsList, newTarget</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;construct()&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">construct</span>(...<span class="hljs-variable language_">arguments</span>);<br>  &#125;,<br>&#125;);<br><span class="hljs-keyword">new</span> <span class="hljs-title function_">proxy</span>(); <span class="hljs-comment">// 触发construct()捕获器</span><br>复制代码<br></code></pre></td></tr></table></figure>

<ol>
<li>返回值<ul>
<li>construct()必须返回一个对象。</li>
</ul>
</li>
<li>拦截的操作<ul>
<li>new proxy(…argumentsList)</li>
<li>Reflect.construct(target, argumentsList, newTarget)</li>
</ul>
</li>
<li>捕获器处理程序参数<ul>
<li>target：目标构造函数</li>
<li>argumentsList：传给目标构造函数的参数列表。</li>
<li>newTarget：最初被调用的构造函数。</li>
</ul>
</li>
<li>捕获器不变式<ul>
<li>target 必须可以用作构造函数。</li>
</ul>
</li>
</ol>
<h1 id="代理反射-VS-Object-defineProperty"><a href="#代理反射-VS-Object-defineProperty" class="headerlink" title="代理反射 VS Object.defineProperty"></a>代理反射 VS Object.defineProperty</h1><p>在上面使用Object.defineProperty的时候，我们遇到的问题有：</p>
<ol>
<li><p>一次只能对一个属性进行监听，需要遍历来对所有属性监听。这个我们在上面已经解决了。</p>
</li>
<li><p>在遇到一个对象的属性还是一个对象的情况下，需要递归监听。</p>
</li>
<li><p>对于对象的新增属性，需要手动监听</p>
</li>
<li><p>对于数组通过push、unshift方法增加的元素，也无法监听</p>
</li>
</ol>
<p>这些问题在Proxy中都轻松得到了解决。</p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li>《Javascript 高级程序设计(第 4 版)》（JS 红宝书）</li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy">MDN - Proxy</a></li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect">MDN - Reflect</a></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/js/">#js</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>代理与反射(一)</div>
      <div>https://airfe.gitee.io/blog/2023/05/02/代理与反射（一）/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月2日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/05/03/%E4%BB%A3%E7%90%86%E4%B8%8E%E5%8F%8D%E5%B0%84%EF%BC%88%E4%BA%8C%EF%BC%89/" title="代理与反射（二）">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">代理与反射（二）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/04/27/%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%8E%E7%94%9F%E6%88%90%E5%99%A8/" title="迭代器与生成器">
                        <span class="hidden-mobile">迭代器与生成器</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
